namespace SimpleWebServices.Web.Mvc
{
    using System;
    using SimpleWebServices.Configuration;
    using SimpleWebServices.Models;
    using SimpleWebServices.Web.Routing;

    public sealed class TenantUriConverter : UriConverter, IConvertUri
    {
        public TenantUriConverter(Type controller, RouteName name)
            : base(controller)
        {
            if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            this.Name = name;
        }

        public AbsoluteUri Urn
        {
            get
            {
                AbsoluteUri value = null;

                if (null != Tenant.Current)
                {
                    ResourcePath resource = this.ToResourcePath(HttpContextFactory.Current.Request.TenantContentPath());
                    if (null != resource)
                    {
                        string urn = RepositoryConfiguration.ToUrn<Tenant>(string.Concat(this.Name, "/", resource.Name));
                        if (urn.EndsWith("/" + this.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            value = new AbsoluteUri(urn.Substring(0, urn.Length - (this.Name.Length + 1)));
                        }
                        else
                        {
                            value = new AbsoluteUri(urn);
                        }
                    }
                }

                return value;
            }
        }

        private RouteName Name
        {
            get;
            set;
        }
    }
}